import classnames from 'classnames';
import { inject, observer } from 'mobx-react';
import React, { Component } from 'react';
// import { toJS } from 'mobx';
import { Route, withRouter } from 'react-router-dom';
import { ActivityIndicator, Avatar, Checkbox, Icon, List, Modal, Result, Toast, Tools } from 'weaver-mobile';
import { BrowserHrm, RouteLayout, Browser } from 'weaver-mobile-page';
import { userType } from '../../../components/form/permission/type';
import UUID from '../../../utils/UUID';
import If, { Else, Then } from '../../if';
import Store from '../store';
import '../style/index.less';
import Footer from './Footer';
import GroupModal from './Group';
import RelatedGroup from './RelatedGroup';
import classNames from 'classnames';
import BackBtn from '../../../components/form/backbtn';
import { TIPS_MSG } from '../../../constants/form';

const { USER, CHATGROUP, DEPARTMENT, SUBCOMPANY } = userType;

const CheckboxItem = Checkbox.CheckboxItem;
const alert = Modal.alert;
const getLabel = Tools.getLabel;

@inject('shareStore')
@withRouter
@observer
export default class ShareButton extends Component {
  static displayName = 'Share';
  static Store = Store;

  static defaultProps = {
    prefixCls: 'wm-share',
    outClassName: '',
  }

  constructor(props) {
    super(props);

    this.store = props.shareStore;
    const { memberList = [], location } = this.props;
    const { pathname, appName, appid } = location;

    this.store.chatGroup = [];
    this.store.users = [];
    this.store.department = [];
    this.store.subCompany = [];

    this.state = {
      memberList,
      pathname,
      appName,
      appid,
      sendForm: false,
      showDetail: false
    };
  }

  componentWillMount () {
    const { init } = this.store;
    const { location } = this.props;
    init(location.pathname);
  }

  deleteNewMember = (data, type) => {
    let { users, chatGroup, department, subCompany } = this.store;

    switch (type) {
      case USER:
        users.forEach((u, index) => {
          if (u.id === data.id) {
            users.splice(index, 1)
          }
        })
        break;
      case CHATGROUP:
        chatGroup.forEach((u, index) => {
          if (u.id === data.id) {
            chatGroup.splice(index, 1)
          }
        })
        break;
      case DEPARTMENT:
        department.forEach((u, index) => {
          if (u.id === data.id) {
            department.splice(index, 1)
          }
        })
        break;
      case SUBCOMPANY:
        subCompany.forEach((u, index) => {
          if (u.id === data.id) {
            subCompany.splice(index, 1)
          }
        })
    }

    if (users.length + chatGroup.length + department.length + subCompany.length <= 0) {
      this.setState({ showDetail: false });
    }

    this.store.chatGroup = chatGroup;
    this.store.users = users;
    this.store.department = department;
    this.store.subCompany = subCompany;

  }

  clearCharGroup = () => {
    this.store.chatGroup = [];
  }

  onChangeChatGroup = (data)=> {
    let { chatGroup } = this.store;

    if(data.isSelect) {
      chatGroup.forEach((cg, index) => {
        if(cg.id === data.id){
          chatGroup.splice(index, 1)
        }
      })
    }else {
      chatGroup.push(data);
    }

    this.store.chatGroup = chatGroup;
  }

  doChatConfirm = (data) => {
    alert(getLabel(391216, '确定发送给：'), data.target_name, [
      { text: getLabel(31129, '取消') },
      { text: getLabel(83446, '确定'),
        onPress: () => {
          const { isInEM } = this.store;

          if (data.target_type === '0') { // 个人
            this.sendMsg('chat', data.target_id, isInEM ? { touserIds: data.target_id } : { touserids: data.target_id });
          } else { // 群
            this.sendMsg('group', data.target_id, isInEM ? { togroupIds: data.target_id } : { togroupids: data.target_id });
          }
        },
      },
    ]);
  }

  doGroupConfirm = (data, routeBack) => {
    alert(getLabel(391216, '确定发送给：'), data.group_name, [
      { text: getLabel(31129, '取消') },
      { text: getLabel(83446, '确定'),
        onPress: () => {
          const { isInEM } = this.store;
          
          this.sendMsg('group', data.group_id, isInEM ? { togroupIds: data.group_id } : { togroupids: data.group_id }, routeBack || -2);
        },
      },
    ]);
  }

  sendMsg = (type, shareId, params, routeBack) => {
    const { msgInfo, msgList, shareParams } = this.props;
    const { sendMsg, getGroupMembers, throwError, isInEM } = this.store;
    let resParams = { ...params };
    if (msgInfo) {
      if (isInEM) {
        resParams = { ...resParams, msgInfo };
      } else { // 企业微信 钉钉 需要的数据格式
        resParams = {
          ...resParams,
          msginfo: [{
            ...msgInfo,
            sharetitle: msgInfo.content || '',
            objectName: 'FW:CustomShareMsg',
          }],
        };
      }
    }
    if (msgList) {
      if (isInEM) {
        resParams = { ...resParams, msgList };
      } else { // 企业微信 钉钉 需要的数据格式
        const msginfo = msgList.map((v) => {
          const item = {
            ...v,
            sharetitle: v.content || '',
            objectName: 'FW:CustomShareMsg',
          };
          return item;
        });
        resParams = { ...resParams, msginfo };
      }
    }
    if (type === 'group') { // 需要通过群id获得群成员ids
      getGroupMembers(shareId).then((res) => {
        if (res.errcode === 0) {
          const share = { ...shareParams, sharegroupid: shareId, resourceids: res.grouplist[0].group_member_ids };
          sendMsg(share, resParams, () => this.props.history.go(routeBack || -1));
        } else {
          throwError(res.errmsg);
        }
      });
    } else {
      const share = { ...shareParams, resourceids: shareId };
      sendMsg(share, resParams, () => this.props.history.go(routeBack || -1));
    }
  }

  onChange = (obj, isSelect) => {
    let { users, chatGroup } = this.store;

    obj.id = obj.target_id;
    obj.type = obj.target_type === '0' ? USER : CHATGROUP;

    if (isSelect) {
      if(obj.type === USER) {
        users.forEach((ml, index) => {
          ml.id === obj.id && (users.splice(index, 1))
        })
      }else {
        chatGroup.forEach((ml, index) => {
          ml.id === obj.id && (chatGroup.splice(index, 1))
        })
      }
    } else {
      if(obj.type === USER){
        users.push(obj);
      }else {
        chatGroup.push(obj);
      }
    }

    this.store.chatGroup = chatGroup;
    this.store.users = users;
  }

  onBack = () => {
    window.history.back(-1);
  }

  setSendForm = () => {
    this.setState({sendForm: !this.state.sendForm});
  }

  setMemberList = (list, callback) => this.setState({ memberList: list }, () => callback && callback())

  onSubmit = () => {
    const { memberList = [], pathname, appid, sendForm } = this.state;
    const { users: u, chatGroup: c, addShareMembers, subCompany: s, department: d} = this.store;
    
    const { onSubmit } = this.props;
    const shareToChat = pathname === '/form/share';
    const users = memberList.filter(p => p.type == USER);
    const chatGroup = memberList.filter(p => p.type === CHATGROUP);
    const userIds = [...users, ...u ].map(u => u.id);
    const chatGroupIds = [...chatGroup,...c ].map(c => c.id);
   
    Toast.loading(TIPS_MSG.PROCESSING, 0);
    if(shareToChat) {
      addShareMembers(
        appid,
        [
          {
            memberId: userIds.join(','),
            memberType: USER
          },
          {
            memberId: chatGroupIds.join(','),
            memberType: CHATGROUP
          }
        ]
      ).then(() => {
        setTimeout(() => {
          window.history.back(-1);
        }, 1000);
      });  
     
      return;
    }

    const subCompany = memberList.filter(p => p.type === SUBCOMPANY);
    const department = memberList.filter(p => p.type === DEPARTMENT);
    const subCompanyIds = [...subCompany,...s ].map(c => c.id);
    const departmentIds = [...department,...d ].map(c => c.id);
    onSubmit([
      {
        memberId: userIds.join(','),
        memberType: USER
      },
      {
        memberId: chatGroupIds.join(','),
        memberType: CHATGROUP
      },
      {
        memberId: subCompanyIds.join(','),
        memberType: SUBCOMPANY
      },
      {
        memberId: departmentIds.join(','),
        memberType: DEPARTMENT
      }
    ], sendForm).then(() => {
      Toast.hide();
      Toast.success(getLabel(526989,'添加人员成功'), 1);
      setTimeout(() => {
        window.history.back(-1);
      }, 1000);
    });
  }

  onAddBrowser = (...arg) => {
    let { users } = this.store;
      users = arg[2];

    this.store.users = users;
    window.history.back(-1);
  }


  onBrowserChange = (type, value) => {
    if (type === 57) {
      this.store.department = value;
    } else if (type === 164) {
      this.store.subCompany = value;
    }
  }

  goto = href => {
    const backBtnAble = window.backBtnAble;

    this.props.history.push(href);

    if (backBtnAble) {
      
      setTimeout(() => {
        const Layout = document.getElementsByClassName('wm-route-layout')[1];

        if (Layout) {
          Layout.style.top = '33px';
          Layout.style.height = 'calc(100% - 33px)';
        }
      });
    }
  }

  renderChatList = (list, wrapCls) => {
    const chatList = list.map((data, index) => {
      const {  memberList = [] } = this.state;
      const { users, chatGroup } = this.store;
      const member = memberList.find(u => u.id === data.target_id)
      const uMember = users.find(u => u.id === data.target_id);
      const chatMember = chatGroup.find(u => u.id === data.target_id);
      let isSelect = false;
      let disabled = false;

      if(member) disabled = true;
      if(uMember || chatMember) isSelect = true;

      return (
        <CheckboxItem
          key={`checkboxItem_${data.target_id}_${index}`}
          disabled={disabled}
          checked={disabled ? true : isSelect}
          onChange={() => this.onChange(data, isSelect)}
         >
          <div className={`${wrapCls}-list`} onClick={() => { !disabled && this.onChange(data, isSelect)}}>
            {
              data.target_type === '0' ? 
              <Avatar userId={data.target_id} /> : 
              <Avatar name={data.target_name || data.group_name} url={data.imgUrl} isGroup={true} type="0" />
            }
            <div className={`${wrapCls}-list-right ${wrapCls}-list-middle`}>
              <span className='person-name'> {data.target_name || data.group_name}</span>
              <If condition={ data.target_type === '0'}>
                <Then>
                  <span className='person-department'>{data.departmentName || ''}</span>
                </Then>
                <Else>
                  <span className='group-size'>{data.member_size ? data.member_size + '人' : ''}</span>
                </Else>
              </If>
            </div>
          </div>
        </CheckboxItem>
      );
    });
    return chatList;
  }

  render() {
    const { prefixCls, className, browserConfig = {}, style, outClassName } = this.props;
    const { browserHrmStore, chatLoading, chatList, users, chatGroup, subCompany, department, browserDeptStore, browserSubcomStore } = this.store;
    const wrapCls = classnames(prefixCls, className);
    const { memberList = [], pathname, sendForm, showDetail } = this.state;
    const shareToChat = pathname === '/form/share';
    const topPx = shareToChat ? 133 : 187;
    const renderLoading = (
      <div className={`${wrapCls}-loading`}>
        <ActivityIndicator text="loading..." size="large" />
      </div>
    );
    const renderNoData = (
      <div className={`${wrapCls}-nodata`}>
        <Result
          img={<Icon type="no-data" />}
          message={getLabel(83553, '暂无数据')}
        />
      </div>
    );
    const renderList = () => {
      if (chatLoading) return renderLoading;
      if (chatList.length === 0) return renderNoData;
      if (chatList.length === 0) return renderNoData;
      return this.renderChatList(chatList, wrapCls);
    };
    const hd = window.getThemeVars ? window.getThemeVars().hd : 1;
    const backBtnAble = window.backBtnAble;
    
    const hasSelected = [...users, ...chatGroup, ...department, ...subCompany].length > 0;
    return (
      <RouteLayout>
        <div className={classNames(`${wrapCls}-chat wm-route-layout wm-edc-share ${outClassName}`, { 'wea-edc-share-back':  backBtnAble })} key="chat" style={style}>
          <If condition={backBtnAble}>
            <BackBtn />
          </If>
          <div className='top-line'></div>
          <BrowserHrm
            store={browserHrmStore}
            hasAdvanceSerach
            type={1}
            isSingle={false}
            valueArray={[]}
            title={getLabel(391210, '创建新的聊天')}
            onChange={this.onAddBrowser}
            notGoBack={true}
            clearToChangeRoute={false}
            {...browserConfig}
          >
            <List.Item
              className={`${wrapCls}-chat-item`}
              thumb={<div className={`${wrapCls}-chat-left`}><Icon type="user" /></div>}
              multipleLine
              onClick={() => this.goto(`${pathname}/add`)}
              arrow={'horizontal'}
            >
              {getLabel(523369, '选择人员')}
            </List.Item>
          </BrowserHrm>
          <If condition={!shareToChat}>
            <Then>
              <Browser
                store={browserDeptStore}
                label="部门"
                hasAdvanceSerach
                type={57}
                isSingle={false}
                onChange={(...arg) => {
                  this.onBrowserChange(57, arg[2]);
                }}
                notGoBack={true}
                clearToChangeRoute={false}
                {...browserConfig}
              >
                <List.Item
                  className={`${wrapCls}-chat-item`}
                  thumb={<div className={`${wrapCls}-chat-left ${wrapCls}-chat-left-dept`}><Icon type="team" /></div>}
                  multipleLine
                  onClick={() => this.goto(`${pathname}/browserDept`)}
                  arrow={'horizontal'}
                >
                  {getLabel(505972, '选择部门')}
                </List.Item>
              </Browser>

              <Browser
                store={browserSubcomStore}
                label="分部"
                hasAdvanceSerach
                type={164}
                isSingle={false}
                onChange={(...arg) => {
                  this.onBrowserChange(164, arg[2]);
                }}
                notGoBack={true}
                clearToChangeRoute={false}
                {...browserConfig}
              >
                <List.Item
                  className={`${wrapCls}-chat-item`}
                  thumb={<div className={`${wrapCls}-chat-left ${wrapCls}-chat-left-subcom`}><Icon type="organization" /></div>}
                  multipleLine
                  onClick={() => this.goto(`${pathname}/browserSubcom`)}
                  arrow={'horizontal'}
                >
                  {getLabel('505970', '选择分部')}
                </List.Item>
              </Browser>
            </Then>
          </If>

          <List.Item
            className={`${wrapCls}-chat-item`}
            thumb={<div className={`${wrapCls}-chat-left ${wrapCls}-chat-left-choose`}><Icon type="group-chat" /></div>}
            multipleLine
            onClick={() => this.goto(`${pathname}/choose`)}
            arrow={'horizontal'}
          >
            {getLabel(391232, '选择群聊')}
          </List.Item>
          <div className={`${wrapCls}-latest`}>{getLabel(526986, '最近')}</div>
          <div 
            className={`${wrapCls}-chat-list`}
            style={{
              top: `${topPx * hd}px`,
              bottom: hasSelected ? 108 : 45,
              marginBottom: hasSelected > 0 ? 25 : 0
              }}> 
            {renderList()} 
          </div>
          <Route
            key="choose"
            path="/form(/power/|/)share/choose"
            render={() => (
              <GroupModal
                {...this.props}
                wrapCls={wrapCls}
                renderLoading={renderLoading}
                renderNoData={renderNoData}
                sendMsg={this.sendMsg}
                doGroupConfirm={this.doGroupConfirm}
                memberList={memberList}
                chatGroup={chatGroup}
                onChangeChatGroup={this.onChangeChatGroup}
                clearCharGroup={this.clearCharGroup}
              />
            )}
          />
          <Route
            key="relatedGroup"
            path={`/form/power/share/relatedGroup`}
            render={() => (
              <RelatedGroup
                {...this.props}
                wrapCls={wrapCls}
                sendMsg={this.sendMsg}
                doGroupConfirm={this.doGroupConfirm}
              />
            )}
          />
          {
            hasSelected ?
            <React.Fragment>
              <span className='btn-box' onClick={() => { this.setState({ showDetail: !showDetail })}}>
                <span className='show-detail-memeber'>
                  <i></i>
                </span>
              </span>
              <div className={classNames('detail-memeber', {'hide-detail-memeber': !showDetail})}>
                <div className='space'></div>
                <ul>
                  {
                    users.map(am => (
                      <li key={`${USER}_${am.id}`} >
                        {<Avatar userId={am.id} />}
                        <div className='person-info'>
                          <span className='person-name'>{am.lastname || am.name}</span>
                          <span className='person-department'>{am.departmentname}</span>
                        </div>
                        <Icon type='cross' size='xs' onClick={() => this.deleteNewMember(am, USER)} />
                      </li>
                    ))
                  }
                  {
                    chatGroup.map(cg => (
                      <li key={`${CHATGROUP}_${cg.id}`}>
                        <Avatar name={cg.group_name || cg.name || cg.lastname} url={cg.imgUrl || cg.icon} isGroup={true} type="0" />
                        <div className='person-info'>
                          <span className='person-name'>{cg.group_name || cg.name || cg.lastname || cg.target_name}</span>
                          <span className='group-size'>{cg.group_member_size || cg.member_size || cg.memberSize}人</span>
                        </div>
                        <Icon type='cross' size='xs' onClick={() => {this.deleteNewMember(cg, CHATGROUP)}}/>
                      </li>
                    ))
                  }
                  {
                    department.map(cg => (
                      <li key={`${DEPARTMENT}_${cg.id}`}>
                        <Avatar name={cg.name } isGroup={true} type="1" />
                        <div className='person-info'>
                          <span className='person-name'>{cg.name}</span>
                          <span className='group-size'>部门</span>
                        </div>
                        <Icon type='cross' size='xs' onClick={() => {this.deleteNewMember(cg, DEPARTMENT)}}/>
                      </li>
                    ))
                  }
                  {
                    subCompany.map(cg => (
                      <li key={`${SUBCOMPANY}_${cg.id}`}>
                        <Avatar name={cg.name } isGroup={true} type="1" />
                        <div className='person-info'>
                          <span className='person-name'>{cg.name}</span>
                          <span className='group-size'>分部</span>
                        </div>
                        <Icon type='cross' size='xs' onClick={() => {this.deleteNewMember(cg, SUBCOMPANY)}}/>
                      </li>
                    ))
                  }
                </ul>
              </div>
              <div className={classNames('detail-member-masker', { 'show-detail-member-masker': showDetail })} onClick={() => {this.setState({showDetail: !showDetail})}}></div>
            </React.Fragment> : null
          }
          <Footer 
            key={UUID()}
            showDetail={showDetail}
            users={users} 
            chatGroup={chatGroup} 
            department={department}
            subCompany={subCompany}
            count={[...users, ...chatGroup, ...department, ...subCompany].length} 
            onSubmit={this.onSubmit}
            shareToChat={shareToChat}
            deleteNewMember={this.deleteNewMember}
            setSendForm={this.setSendForm}
            sendForm={sendForm}
            onBack={() => window.history.back(-1)} />
        </div>
      </RouteLayout>
    );
  }
}
